package com.jmemoir.safe.paramsencrypt.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * AES 加解密工具类
 *
 * @author Tellsea
 * @date 2023/8/6
 */
@Slf4j
public class AesUtils {

    public static String encrypt(String key, String data) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] encryptedData = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encryptedData);
    }

    public static String decrypt(String key, String encryptedData) throws Exception {
        encryptedData = URLDecoder.decode(encryptedData, "UTF-8");
        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] decryptedData = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
        return new String(decryptedData, StandardCharsets.UTF_8);
    }

    public static void main(String[] args) throws Exception {
        JSONObject json = new JSONObject();
        json.putOnce("timestamp", DateUtil.current());
//        String encrypt = encrypt(ParamEncryptFilter.AES_KEY, JSONUtil.toJsonStr(json));
//        String encode = URLEncoder.encode("ZQsqo66YoaT90a/T1YqACruLgInUpD8D9EDGdPykNfQwjUrmWzmAFYLRw20+QQud0GkIurLGMQDAp/iwuB1GTmFkASTZYnMfA6G33uQNyZU=", "UTF-8");
//        System.out.println(decrypt(ParamEncryptFilter.AES_KEY, URLDecoder.decode(encode, "UTF-8")));
    }
}
